package cn.wolfcode.controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import cn.wolfcode.domain.Order;
import cn.wolfcode.service.IOrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 订单控制器类
 * @Author: 伍家钰
 * @Date: 2020/8/28 18:42
 * @Version: 1.0
 */
@RestController
@RequestMapping("orders")
@Slf4j
public class OrderController {
    @Autowired
    private IOrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    //降级配置
    @HystrixCommand(fallbackMethod = "saveFallback")
    @GetMapping("/save/{uid}/{pid}")
    public Order save(@PathVariable("uid") Long userId, @PathVariable("pid") Long productId,
                      HttpServletRequest request) {
        System.out.println("尝试恢复路线......");
        String cookie = request.getHeader("cookie");
        String token = request.getHeader("token");
        System.out.println(cookie + "------->" + token);
        //传入用户id为负数走降级, 其他值正常
        if (userId < 0) {
            int i = 1 / 0;
        }
        //记录调用日志
        log.info("OrderController-save.....");
        return orderService.save(userId, productId);
    }

    // 执行降级功能时的响应方法,其中的业务逻辑根据实际需求来设计
    public Order saveFallback(@PathVariable Long userId, @PathVariable Long productId, HttpServletRequest request) {
        System.out.println("走降级方法......");
        // 用短信通知运维人员来维护,频率是20s,创建一个新线程,防止短信发送失败时,其他线程功能受影响
        new Thread(new Runnable() {
            @Override
            public void run() {
                String redisKey = "order-save";
                String value = stringRedisTemplate.opsForValue().get(redisKey);
                if (StringUtils.isEmpty(value)) {
                    System.out.println("order下订单服务失败，请查找原因.");
                    stringRedisTemplate.opsForValue().set(redisKey, "save-order-fail", 20, TimeUnit.SECONDS);
                } else {
                    System.out.println("已经发送过短信");
                }
            }
        }).start();
        return new Order();
    }
}
